package com.example.springboottest.util;

import com.example.springboottest.bean.util.ReqRespResearchProductQuestionnaireItem;
import org.apache.commons.lang3.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class IntervalUtil {
    public static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");

    /**
     * @Description: 比较dataValue与interval结果
     * @Param: [dataValue：比较值， interval：如 ≤0、≥0 、>0 、<0 、==0]
     * @return: boolean
     */
    public static boolean compareNumValue(String dataValue, String interval) {
        //转换比较符号≤转换为<=，≥转换为>=
        String comparator = interval.replace("≤", "<=").replace("≥", ">=");
        //拼接表达式
        StringBuffer formula = new StringBuffer();
        formula.append("(");
        formula.append(dataValue);
        formula.append(comparator);
        formula.append(")");
        try {
            //计算表达式
            return (Boolean) jse.eval(formula.toString());
        } catch (Exception t) {
            return false;
        }
    }

    /**
     * 判断data_value是否在interval区间范围内
     *
     * @param data_value 数值类型的
     * @param interval   正常的数学区间，包括无穷大等，如：(1,3)、>5%、(-∞,6]、(125%,135%)U(70%,80%)
     * @return true：表示data_value在区间interval范围内，false：表示data_value不在区间interval范围内
     */
    public static boolean isInTheInterval(String data_value, String interval) {
        //将区间和data_value转化为可计算的表达式
        String formula = getFormulaByAllInterval(data_value, interval, "||");
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        try {
            //计算表达式
            return (Boolean) jse.eval(formula);
        } catch (Exception t) {
            return false;
        }
    }

    public static String eval(String el) {

        try {
            return new DecimalFormat("0.00").format(jse.eval(el));
        } catch (ScriptException e) {
            e.printStackTrace();

            return "0.00";
        }
    }


    /**
     * 将所有阀值区间转化为公式：如
     * [75,80)   =》        date_value < 80 && date_value >= 75
     * (125%,135%)U(70%,80%)   =》        (date_value < 1.35 && date_value > 1.25) || (date_value < 0.8 && date_value > 0.7)
     *
     * @param date_value
     * @param interval   形式如：(125%,135%)U(70%,80%)
     * @param connector  连接符 如：") || ("
     */
    private static String getFormulaByAllInterval(String date_value, String interval, String connector) {
        StringBuffer buff = new StringBuffer();
        for (String limit : interval.split("U")) {//如：（125%,135%）U (70%,80%)
            buff.append("(").append(getFormulaByInterval(date_value, limit, " && ")).append(")").append(connector);
        }
        String allLimitInvel = buff.toString();
        int index = allLimitInvel.lastIndexOf(connector);
        allLimitInvel = allLimitInvel.substring(0, index);
        return allLimitInvel;
    }

    /**
     * 将整个阀值区间转化为公式：如
     * 145)      =》         date_value < 145
     * [75,80)   =》        date_value < 80 && date_value >= 75
     *
     * @param date_value
     * @param interval   形式如：145)、[75,80)
     * @param connector  连接符 如：&&
     */
    private static String getFormulaByInterval(String date_value, String interval, String connector) {
        StringBuffer buff = new StringBuffer();
        for (String halfInterval : interval.split(",")) {//如：[75,80)、≥80
            buff.append(getFormulaByHalfInterval(halfInterval, date_value)).append(connector);
        }
        String limitInvel = buff.toString();
        int index = limitInvel.lastIndexOf(connector);
        limitInvel = limitInvel.substring(0, index);
        return limitInvel;
    }

    /**
     * 将半个阀值区间转化为公式：如
     * 145)      =》         date_value < 145
     * ≥80%      =》         date_value >= 0.8
     * [130      =》         date_value >= 130
     * <80%     =》         date_value < 0.8
     *
     * @param halfInterval 形式如：145)、≥80%、[130、<80%
     * @param date_value
     * @return date_value < 145
     */
    private static String getFormulaByHalfInterval(String halfInterval, String date_value) {
        halfInterval = halfInterval.trim();
        if (halfInterval.contains("∞")) {//包含无穷大则不需要公式
            return "1 == 1";
        }
        StringBuffer formula = new StringBuffer();
        String data = "";
        String opera = "";
        if (halfInterval.matches("^([<>≤≥\\[\\(]{1}(-?\\d+.?\\d*\\%?))$")) {//表示判断方向（如>）在前面 如：≥80%
            opera = halfInterval.substring(0, 1);
            data = halfInterval.substring(1);
        } else {//[130、145)
            opera = halfInterval.substring(halfInterval.length() - 1);
            data = halfInterval.substring(0, halfInterval.length() - 1);
        }
        double value = dealPercent(data);
        formula.append(date_value).append(" ").append(opera).append(" ").append(value);
        String a = formula.toString();
        //转化特定字符
        return a.replace("[", ">=").replace("(", ">").replace("]", "<=").replace(")", "<").replace("≤", "<=").replace("≥", ">=");
    }

    /**
     * 去除百分号，转为小数
     *
     * @param str 可能含百分号的数字
     * @return
     */
    private static double dealPercent(String str) {
        double d = 0.0;
        if (str.contains("%")) {
            str = str.substring(0, str.length() - 1);
            d = Double.parseDouble(str) / 100;
        } else {
            d = Double.parseDouble(str);
        }
        return d;
    }

    public static boolean isOverlap(List<String> laplist) {
        List<ReqRespResearchProductQuestionnaireItem> list = new ArrayList<>();

        for (String lap : laplist) {
            list.add(convertlaps(lap));
        }

        return SectionUtil.compareSection(list);

    }

    public static ReqRespResearchProductQuestionnaireItem convertlaps(String lap) {
        // 7-全闭区间/8-左闭右开区间/9-左开右闭区间/10-全开区间
        String min = "";
        String max = "";

        String el = "";

        el = String.valueOf(lap.charAt(0)) + String.valueOf(lap.charAt(lap.length() - 1));


        Byte type = new Byte("0");
        if (el.equals("[]")) {

            type = new Byte("7");
        } else if (el.equals("[)")) {

            type = new Byte("8");
        } else if (el.equals("(]")) {

            type = new Byte("9");
        } else if (el.equals("()")) {

            type = new Byte("10");
        } else {

            throw new RuntimeException("区间表达式格式异常------->" + lap);
        }


        String[] s1s = lap.split(",");


        min = s1s[0].substring(1);

        max = s1s[1].substring(0, s1s[1].length() - 1);


        System.out.println(min + "---" + max + "---" + el + "-- 7-全闭区间/8-左闭右开区间/9-左开右闭区间/10-全开区间 --" + type);

        return new ReqRespResearchProductQuestionnaireItem(min, max, type);
    }



    /**
     * 解析偏差判据中的值，装成一个区间
     *
     * @param interval
     * @author liuyishuo
     * @date 2023/7/7 17:40
     * @return java.util.List<java.lang.String>
     **/
    public static  List<String> isIRadiusCalculation(String interval){

        String loseStr = "";
        String justStr = "";
        // 负无穷大
        if (interval.contains("-∞")) {

            int headInt = StringUtils.ordinalIndexOf(interval, ",", 1);
            int endInt = StringUtils.ordinalIndexOf(interval, ")", 1);
            loseStr = interval.substring(headInt+1, endInt);
        }

        // 正无穷大
        if (interval.contains("+∞")) {

            int headInt = StringUtils.ordinalIndexOf(interval, "(", 2);
            int endInt = StringUtils.ordinalIndexOf(interval, ",", 2);
            justStr = interval.substring(headInt+1, endInt);
        }


        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");

        if (interval.contains("U")) {

            if (StringUtils.isNotBlank(loseStr) && StringUtils.isNotBlank(justStr)) {
                stringBuffer.append(loseStr);
                stringBuffer.append(",");
                stringBuffer.append(justStr);
            }

        }else {
            if (StringUtils.isNotBlank(loseStr)) {
                stringBuffer.append(loseStr);
            }
            if (StringUtils.isNotBlank(justStr)) {
                stringBuffer.append(justStr);
            }
        }
        stringBuffer.append("]");

        List<String> resultList = new ArrayList<>();

        if (StringUtils.isNotBlank(stringBuffer)) {
            resultList.add(stringBuffer.toString());
        }
        return resultList;
    }


    /**
     * 获取参数的数组
     *
     * @param modelParams
     * @author liuyishuo
     * @date 2023/7/7 18:08
     * @return java.util.List<java.lang.String>
     *
     *
     *     [-3<= x <= 3]
     *     [-3&lt;=x&lt;=3]
     *
     **/
    public static  List<String> getModelParams(String modelParams){

        String loseStr = "";
        String justStr = "";

        String paramTo = StringUtil.getParamTo(modelParams);

        if (paramTo.contains("||")) {
            int headInt = StringUtils.ordinalIndexOf(paramTo, ">", 1);
            int endInt = StringUtils.ordinalIndexOf(paramTo, "||", 1);
            loseStr = paramTo.substring(headInt+1, endInt);


            int headInt2 = StringUtils.ordinalIndexOf(paramTo, "<", 1);
            int endInt2 = StringUtils.ordinalIndexOf(paramTo, "]", 1);
            justStr = paramTo.substring(headInt2+1, endInt2);

        }else {

            int headInt = StringUtils.ordinalIndexOf(paramTo, "<", 1);
            loseStr = paramTo.substring(0, headInt);


            int headInt2 = StringUtils.ordinalIndexOf(paramTo, "=", 2);
            justStr = paramTo.substring(headInt2+1);

        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");

        if (paramTo.contains("||")) {

            if (StringUtils.isNotBlank(loseStr) && StringUtils.isNotBlank(justStr)) {
                stringBuffer.append(loseStr);
                stringBuffer.append(",");
                stringBuffer.append(justStr);
            }

        }else {
            if (StringUtils.isNotBlank(loseStr)) {
                stringBuffer.append(loseStr);
            }
            if (StringUtils.isNotBlank(justStr)) {
                stringBuffer.append(",");
                stringBuffer.append(justStr);
            }
        }
        stringBuffer.append("]");

        List<String> resultList = new ArrayList<>();

        if (StringUtils.isNotBlank(stringBuffer)) {
            resultList.add(stringBuffer.toString());
        }
        return resultList;
    }





    public static void main(String[] args) {
        IntervalUtil a = new IntervalUtil();

        String eval = "x∈[(-∞,-2.5)U(2.5,+∞)]";
        String eval1 = "x∈[(-∞,-2.5)]";
        String eval2 = "x∈[(2.5,+∞)]";
        String eval3 = "-3<=x";

        //无穷小
        System.out.println(isInTheInterval("3", eval3));
        //判断区间范围
        System.out.println(isInTheInterval("1", eval));
        //比较dataValue与interval结果
//        String eval = "≥0";
//        System.out.println(compareNumValue("5", eval));


//        eval = "(2*2*2*2)/3-2";
//
//        System.out.println(eval(eval));
//
//        String s1 = "(0.23,90.88]";
//
//
//
//        System.out.println("===========================");
//        convertlaps(s1);
//
//
//        String el = "(2>1)&&(3<2)";
//        String el1 = "(#score>1)||(#check_status<2)";
//        String el2 = "(1,2) U (2,5)U (3,10)";
//
//
//        try {
//            System.out.println("el-------------->" + jse.eval(el2));
//
////            System.out.println("el-------------->"+ ElUtil.pick(el1));
//
//
////            System.out.println(isInTheInterval("13.1", el2));
//
//        } catch (ScriptException e) {
//            throw new RuntimeException(e);
//        }


    }
}
